<template>
	<el-cascader
		ref="cascader"
		:options="options"
		:show-all-levels="false"
		filterable
		clearable
		collapse-tags
		collapse-tags-tooltip
		@change="cascaderChange"
		v-bind="$attrs"
	>
		<template v-for="slotKey in Object.keys($slots)" :key="slotKey" v-slot:[slotKey]>
			<slot :name="slotKey"></slot>
		</template>
	</el-cascader>
</template>

<script setup name="MyCascader">
import _camelCase from 'lodash/camelCase';

const emits = defineEmits(['getLabel']),
	attrs = useAttrs(),
	/***
	 * 参数属性
	 * @property {list[]} list 数据源
	 * @property {String} type store.dispatch的方法名
	 */
	props = defineProps({
		type: {
			type: String
		},
		list: {
			type: Array,
			default: () => []
		}
	}),
	cascader = shallowRef(null);

let dictType = computed(() => {
		if (props?.type) {
			if (props?.type?.startsWith('GET')) return props.type;
			return `GET${_camelCase(props.type)}`;
		}
	}),
	options = ref([]);

watch(
	() => props.list,
	(val) => {
		options.value = val;
	},
	{ deep: true, immediate: true }
);
watch(
	() => $store?.com[unref(dictType)?.replace('GET', '')],
	(val) => {
		if (unref(dictType)) options.value = val;
	},
	{ deep: true, immediate: true }
);

/**
 * 初始化执行逻辑
 */
if (unref(dictType)) $store?.com[unref(dictType)]();

function cascaderChange() {
	if (!attrs.props.multiple) {
		emits('getLabel', unref(cascader).getCheckedNodes()[0]?.label || '');
		unref(cascader).togglePopperVisible(false);
	} else {
		emits('getLabel', unref(cascader).getCheckedNodes() || []);
	}
}
</script>
